//
//  STRichViewController.m
//  STNewTools
//
//  Created by apple on 17/7/6.
//  Copyright © 2017年 stoneobs. All rights reserved.
//

#import "STRichViewController.h"
#import "AFNetworking.h"
#import "UIViewController+STNavigationTools.h"
#define kUrlStrA @"http://c.apiplus.net/daily.do"
#define kToken @"3fa91592fbaf99c6"
#import "STPickerViewController.h"
#import "UIView+STDirection.h"
#import "NSDate+STFormatter.h"
#import "STButton.h"

@interface STRichViewController ()
@property(nonatomic,strong)NSMutableArray * dataSouce;
@property(nonatomic,strong)NSDate * date;
@property(nonatomic,strong)UILabel * numLable;
@end

@implementation STRichViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setRightItemWithTitle:@"日期" titleColor:[UIColor redColor]];
    self.date = [NSDate date];
    [self netWorkRequestWithDate:self.date];
    
    NSLog(@"test");
    
    UIView * header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.width, 130)];
    header.backgroundColor = self.tableView.backgroundColor;
    
    STButton * last = [[STButton alloc] initWithFrame:CGRectMake(30, 24, 100, 40) title:@"lastday" titleColor:[UIColor orangeColor] titleFont:18 cornerRadius:3 backgroundColor:nil backgroundImage:nil image:nil];
    [header addSubview:last];
    
    STButton * next = [[STButton alloc] initWithFrame:CGRectMake(30, 24, 100, 40) title:@"nextDay" titleColor:[UIColor orangeColor] titleFont:18 cornerRadius:3 backgroundColor:nil backgroundImage:nil image:nil];
    next.right = self.tableView.width - 30;
    [header addSubview:next];
    
    self.tableView.tableHeaderView = header;
    __weak typeof(self) weakSelf = self;
    
    [last setClicAction:^(UIButton *sender) {
        weakSelf.date = [NSDate dateWithTimeIntervalSince1970:weakSelf.date.timeIntervalSince1970 - 24*60*60];
        [weakSelf netWorkRequestWithDate:weakSelf.date];
    }];
    [next setClicAction:^(UIButton *sender) {
        weakSelf.date = [NSDate dateWithTimeIntervalSince1970:weakSelf.date.timeIntervalSince1970 + 24*60*60];
        [weakSelf netWorkRequestWithDate:weakSelf.date];
    }];
    
    self.numLable = [[UILabel alloc] initWithFrame:CGRectMake(30, 80, 300, 20)];
    self.numLable.textColor = [UIColor blackColor];
    [header addSubview:self.numLable];
    STButton * refresh = [[STButton alloc] initWithFrame:CGRectMake(30, 24, 100, 40) title:@"刷新" titleColor:[UIColor orangeColor] titleFont:18 cornerRadius:3 backgroundColor:nil backgroundImage:nil image:nil];
    
    refresh.top = self.numLable.bottom + 5;
    [refresh setClicAction:^(UIButton *sender) {
        [weakSelf netWorkRequestWithDate:weakSelf.date];
    }];
    [header addSubview:refresh];
    // Do any additional setup after loading the view.
}

#pragma mark ---tableview datasouse and delegate start
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSouce.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 24;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell * cell =[tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
    }
    cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
//    NSDictionary * dic = @{@"expect":expect,
//                           @"num":@(num)};
    cell.textLabel.text = [self.dataSouce[indexPath.row] valueForKey:@"expect"];
    cell.detailTextLabel.text = [[self.dataSouce[indexPath.row] valueForKey:@"num"] description];
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}
- (void)rightBarAction:(id)sender{

    STPickerViewController * pic = [[STPickerViewController alloc] initWithDefualtDatePickerWithHandle:^(NSDate *date) {
        self.title = date.yyyyMMddByLineWithDate;
        self.date = date;
        [self netWorkRequestWithDate:date];
    }];
    [self presentViewController:pic animated:NO completion:nil];
}
- (void)netWorkRequestWithDate:(NSDate*)date{

    self.title = date.yyyyMMddByLineWithDate;
  
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    [mgr.requestSerializer setTimeoutInterval:10];
    
    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString * url = kUrlStrA;
    //mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"text/plain", @"application/json", nil];
 
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    
    [dateformatter setDateFormat:@"YYYY-MM-dd"];
    
    NSString * caiRiqi = [dateformatter stringFromDate:date];
    NSMutableDictionary *inputDict = [NSMutableDictionary dictionary];
    inputDict[@"token"]  = kToken;
    inputDict[@"code"]   = @"twbingo";
    inputDict[@"date"]   = caiRiqi;
    inputDict[@"format"] = @"json";
    [mgr GET:url  parameters:inputDict progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        

        //成功
        //NSString * dataStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        
        NSDictionary * dataDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        
        NSArray *tempArr = dataDic[@"data"];
        NSLog(@"一共有%ld",tempArr.count);
        self.dataSouce = [NSMutableArray new];
        if (tempArr.count == 0) {
            
        }else{
            
            NSMutableDictionary *tempDict = [NSMutableDictionary dictionary];
            NSMutableArray *qishuArr = [NSMutableArray array];
            NSMutableArray *haomaArr = [NSMutableArray array];
            [qishuArr removeAllObjects];
            [haomaArr removeAllObjects];
            
            for (NSInteger i = 0; i <tempArr.count; i++) {
                
                NSString *tempStr1 = tempArr[i][@"opencode"];
                NSArray *tempArr1  = [tempStr1 componentsSeparatedByString:@","];
                NSInteger tempInt1 = [tempArr1[0] integerValue] +
                [tempArr1[1] integerValue]+
                [tempArr1[2] integerValue]+
                [tempArr1[3] integerValue];
                NSInteger tempNum1 = tempInt1 % 10;
                
                NSInteger tempInt2 = [tempArr1[4] integerValue] +
                [tempArr1[5] integerValue]+
                [tempArr1[6] integerValue]+
                [tempArr1[7] integerValue];
                NSInteger tempNum2 = tempInt2 % 10;
                
                NSInteger tempInt3 = [tempArr1[8] integerValue] +
                [tempArr1[9] integerValue]+
                [tempArr1[10] integerValue]+
                [tempArr1[11] integerValue];
                NSInteger tempNum3 = tempInt3 % 10;
                
                NSInteger tempInt4 = [tempArr1[12] integerValue] +
                [tempArr1[13] integerValue]+
                [tempArr1[14] integerValue]+
                [tempArr1[15] integerValue];
                NSInteger tempNum4 = tempInt4 % 10;
                
                NSInteger tempInt5 = [tempArr1[16] integerValue] +
                [tempArr1[17] integerValue]+
                [tempArr1[18] integerValue]+
                [tempArr1[19] integerValue];
                NSInteger tempNum5 = tempInt5 % 10;
                
                NSString *tempStr2 = [NSString stringWithFormat:@"%ld,%ld,%ld,%ld,%ld",(long)tempNum1,(long)tempNum2,(long)tempNum3,(long)tempNum4,(long)tempNum5];
                
                if (tempInt1 % 2 == 0 &&
                    tempInt2 % 2 == 0 &&
                    tempInt3 % 2 == 0 &&
                    tempInt4 % 2 == 0 &&
                    tempInt5 % 2 == 0 ) {
                    
                    NSString * expect = tempArr[i][@"expect"];
                    NSInteger lastExpect = self.dataSouce.lastObject ? [[self.dataSouce.lastObject valueForKey:@"expect"] integerValue]:0;
                    
                    NSInteger num = lastExpect? ABS([expect integerValue] - lastExpect):0;
                    NSDictionary * dic = @{@"expect":expect,
                                           @"num":@(num)};
                    [self.dataSouce addObject:dic];
                }

                
               
                
            }
            
        }
        [self.tableView reloadData];
        self.numLable.text = [NSString stringWithFormat:@"今日已经中了%ld期，总共203期",self.dataSouce.count];
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        
    }];

}
@end
